package client.comm.baoding.adapter

import android.content.Context
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.setPadding
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import client.comm.commlib.base.BaseAdapter
import client.comm.commlib.base.BindingViewHoder
import client.comm.commlib.base.SyBannerAdapter
import client.comm.commlib.comm_ui.ImageGalleryActivity
import client.comm.baoding.R
import client.comm.baoding.api.bean.GoodsDetail
import client.comm.baoding.databinding.LayoutGoodsImgItemBinding
import client.comm.baoding.databinding.LayoutGoodsdetailsHeaderBinding
import client.comm.baoding.ui.GoodDetailImgsActivity
import client.comm.baoding.ui.GoodsDetailActivity
import client.comm.commlib.dipToPx
import client.comm.commlib.getScreenWidth
import com.bumptech.glide.RequestManager
import com.bumptech.glide.request.RequestOptions
import com.youth.banner.indicator.CircleIndicator
import java.util.ArrayList

class GoodsDetailAdapter : BaseAdapter<GoodsDetail.Detail> {

    val manager: RequestManager

    var goodsDetail: GoodsDetail? = null
//    var goodsDetail: GoodsDetail

    constructor(context: Context, manager: RequestManager) : super(context) {
        this.manager = manager
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        if (viewType == 0)
            return BindingViewHoder(
                DataBindingUtil.inflate(
                    layoutInflater,
                    R.layout.layout_goodsdetails_header,
                    parent,
                    false
                )
            ).apply {
                val itemBinding = binding as LayoutGoodsdetailsHeaderBinding

                with(itemBinding) {
                    val width = getScreenWidth(context)
                    val params: ViewGroup.LayoutParams = itemBinding.banner.getLayoutParams()
                    params.height = (width)
                    banner.layoutParams = params
                    banner.setIndicator(CircleIndicator(context))
                }
            }

        return BindingViewHoder(
            DataBindingUtil.inflate(
                layoutInflater,
                R.layout.layout_goods_img_item,
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val bindingViewHolder = holder as BindingViewHoder<ViewDataBinding>
        if (bindingViewHolder.getItemViewType() === 0) {
            val binding = bindingViewHolder.binding as LayoutGoodsdetailsHeaderBinding
            val list = goodsDetail?.banner_list

            if (list != null) {
                binding.banner.setAdapter(object : SyBannerAdapter<GoodsDetail.Banner>(list) {
                    override fun onBindView(
                        holder: BannerViewHolder?,
                        data: GoodsDetail.Banner?,
                        position: Int,
                        size: Int
                    ) {
                        manager.load(data?.goods_img)
                            .apply(RequestOptions().error(R.mipmap.ic_launcher))
                            .into(
                                holder!!.imageView
                            )
                    }
                })
            }
            binding.banner.start()
            binding.event = this
            binding.goodName.text = goodsDetail?.name

            binding.apply {
                tvSku.text = goodsDetail?.sku
                tvStock.text = "库存：${goodsDetail?.stock_c}"
            }
            goodsDetail?.goods_label?.let {
                binding.llLabel.removeAllViews()
                for (e in it) {
                    binding.llLabel.addView(getLabel(e))
                }
            }

            binding.commPriceIntegral.apply {
                var is_price_show: Boolean = false
                var is_integral_unit_show: Boolean = false
//                goodsDetail.price = 0.0
//                goodsDetail.lpq_price=1.0

                if (goodsDetail?.price!! > 0) {
                    tvPrice.text = "${goodsDetail?.price}"
                    is_price_show = true
                    if (goodsDetail?.integral!! > 0) {
                        tvIntegral.text = "+" + goodsDetail?.integral //+ "积分"
                        is_integral_unit_show = true
                    } else {
                        tvIntegral.text = ""
                        is_integral_unit_show = false
                    }
                } /*else if (goodsDetail.lpq_price > 0) {
                    TextTool.getBuilder("${goodsDetail.lpq_price}")
                        .setAlign(Layout.Alignment.ALIGN_CENTER).setTextSize(18)
                        .append("体验券").setForegroundColor(Color.parseColor("#E81837"))
                        .setTextSize(12)
                        .into(tvPrice)
                    is_price_show = true
                    if (goodsDetail.integral > 0) {
                        tvIntegral.text = "+" + goodsDetail.integral //+ "积分"
                        is_integral_unit_show = true
                    } else {
                        tvIntegral.text = ""
                        is_integral_unit_show = false
                    }

                }*/ else {
                    tvPrice.text = ""
                    is_price_show = false
                    if (goodsDetail!!.integral > 0) {
                        tvIntegral.text = "" + goodsDetail!!.integral //+ "积分"
                        is_integral_unit_show = true
                    } else {
                        tvIntegral.text = ""
                        is_integral_unit_show = false
                    }
                }

                if (is_price_show) {
                    tvPriceUnit.visibility = View.VISIBLE
                } else {
                    tvPriceUnit.visibility = View.GONE
                }

                if (is_integral_unit_show) {
                    tvIntegralDesc.visibility = View.VISIBLE
                } else {
                    tvIntegralDesc.visibility = View.GONE
                }
            }


//            binding.toldPrice.text = "￥20"
//            binding.toldPrice.getPaint()
//                .setFlags(Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) //中划线
//            if (goodsDetail.integral > 0)
//                binding.yxTxt.text = "积分${goodsDetail.integral}"

        } else {
            val binding: LayoutGoodsImgItemBinding =
                bindingViewHolder.binding as LayoutGoodsImgItemBinding
            val path = getItem(position).goods_img
//            binding.path = path
//            binding.event = this
            manager.load(path)
                .into(binding.img)
        }
    }

    //设置商品label标签
    private fun getLabel(str: String): View? {
        val child = TextView(context)
        child.textSize = 12f
        var drawId = when (str) {
            "热卖" -> R.drawable.label_bg_red1_0
            "新品" -> R.drawable.label_bg_green1_0
            "爱心商品" -> R.drawable.label_bg_blue1_0
            else -> null
        }
        if (drawId != null) {
            child.background = ContextCompat.getDrawable(context, drawId)
        }
        child.setTextColor(ContextCompat.getColor(context, R.color.white))
        child.setText(str)
        child.setPadding(dipToPx(context.resources!!, 2f).toInt())
        // 定义LayoutParam
        val params: RelativeLayout.LayoutParams =
            RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        params.rightMargin = dipToPx(context.resources!!, 10f).toInt()
        child.layoutParams = params
        // 调用带有LayoutParams参数的addView方法
        return child//mContainer.addView(child, params)
    }

    fun setData(list: MutableList<GoodsDetail.Detail?>, goodsDetail: GoodsDetail) {
        this.goodsDetail = goodsDetail
        list.add(0, null)
        submitList(list)
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == 0) 0 else 1
    }

//    fun goDy() {
//        try {
//            val intent = Intent()
//            // 93325972684 这个是抖音中的userID 不25是抖音号!!
//            // 93325972684 这个是抖音中的userID 不是抖音号!!
//            intent.data = Uri.parse("snssdk1128://user/profile/88531254126")
//            context.startActivity(intent)
//        } catch (e: Exception) {
//            e.message?.let {
//                if (it.contains("snssdk1128://user/profile/"))
//                    toast("未安装抖音")
//            }
//        }
//    }

    fun itemClick(bean: String) {
        val banners: List<GoodsDetail.Detail?> = getItems()
        val imgs = arrayOfNulls<String>(banners.size - 1)
        for (i in 1 until banners.size) {
            val `in`: Int = i - 1
            val p: String = banners[i]!!.goods_img
            imgs[`in`] = p
        }
        ImageGalleryActivity.show(
            context,
            imgs as Array<String>?,
            imgs.indexOf(bean),
            true,
            false
        )
    }

    //商品详情之图片
    fun goodDetail() {
        goodsDetail?.let {
            context.startActivity(Intent(context, GoodDetailImgsActivity::class.java).apply {
                putExtra("banner_list", it.banner_list as ArrayList<GoodsDetail.Banner>)
                putExtra("detail_list", it.detail_list as ArrayList<GoodsDetail.Detail>)
            })
        }
    }

}